<template>
    <div class="role-manage">
        <div class="query-form">
            <el-form ref="form" :inline="true" :model="queryForm">
                <el-form-item  label="角色名称" prop="roleName">
                    <el-input v-model="queryForm.roleName" placeholder="请输入角色名称"/>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="handleQuery">查询</el-button>
                    <el-button @click="handleReset('form')">重置</el-button>
                </el-form-item>
            </el-form>
        </div>
        <div class="base-table">
            <div class="action">
                <el-button type="primary" @click="handleCreate">新增</el-button>
                <el-button type="danger" @click="handlePatchDelete">批量删除</el-button>
            </div> 
            <el-table :data="roleList" @selection-change="handleSelectionChange" border cell-style="padding: 4px 0"  max-height="600">
                <el-table-column type="selection" width="40" align="center"/>
                <el-table-column 
                    v-for="item in columns" 
                    :key="item.prop" 
                    :prop="item.prop" 
                    :label="item.label" 
                    :width="item.width"
                    :formatter="item.formatter" align="center"/>
                <el-table-column label="操作" width="150" align="center">
                    <template #default="scope">
                        <el-button size="mini" type="primary" :disabled="scope.row.systemic" @click="handleEdit(scope.row)">编辑</el-button>
                        <el-button size="mini" type="danger" :disabled="scope.row.systemic" @click="handleDelete(scope.row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <el-pagination
                class="pagination"
                background
                layout="prev, pager, next"
                :total="pager.totalCount"
                :page-size="pager.pageSize"
                @current-change="handleCurrentChange"/>
        </div>
        <el-dialog :title="action=='add' ? '角色新增' : '角色修改'"
            v-model="showModal" 
            :close-on-click-modal="false"
            :show-close="false" width="500px" center>
            <el-form ref="dialogForm" :model="roleForm" label-width="100px" :rules="rules">
                <el-form-item label="角色名称" prop="roleName">
                    <el-input v-model="roleForm.roleName" placeholder="请输入角色名称"/>
                </el-form-item>
                <el-form-item label="菜单权限" prop="menuCheckedKeys">
                    <el-checkbox v-model="menuExpand" @change="handleMenuCheckedTreeExpand($event)">展开全部</el-checkbox>
                    <el-checkbox v-model="menuNodeAll" @change="handleMenuCheckedTreeNodeAll($event)">选中全部</el-checkbox>
                    <el-checkbox v-model="menuCheckStrictly" @change="handleMenuCheckedTreeConnect($event)">父子联动</el-checkbox>
                    <el-tree
                        class="tree-border"
                        :data="menuOptions"
                        ref="menuRef"
                        show-checkbox
                        node-key="menuId"
                        :default-checked-keys="roleForm.menuCheckedKeys"
                        :check-strictly="!menuCheckStrictly"
                        empty-text="加载中，请稍候"
                        :props="{ label: 'menuName', children: 'children' }"
                    />
                </el-form-item>
                <el-form-item label="权限类型" prop="dataAuth">
                    <el-select v-model="roleForm.dataAuth" size="medium" style="width: 100%;">
                        <el-option label="全部数据权限" value='1'></el-option>
                        <el-option label="自定义数据权限" value='2'></el-option>
                        <el-option label="本下级数据权限" value='3'></el-option>
                        <el-option label="仅本级数据权限" value='4'></el-option>
                        <el-option label="仅本人数据权限" value='5'></el-option>
                    </el-select>
			    </el-form-item>
                <el-form-item label="数据权限" prop="groupCheckedKeys" v-show="roleForm.dataAuth == '2'">
                    <el-checkbox v-model="groupExpand" @change="handleGroupCheckedTreeExpand($event)">展开全部</el-checkbox>
                    <el-checkbox v-model="groupNodeAll" @change="handleGroupCheckedTreeNodeAll($event)">选中全部</el-checkbox>
                    <el-checkbox v-model="groupCheckStrictly" @change="handleGroupCheckedTreeConnect($event)">父子联动</el-checkbox>
                    <el-tree
                        class="tree-border1"
                        :data="groupOptions"
                        ref="groupRef"
                        show-checkbox
                        node-key="groupId"
                        :default-checked-keys="roleForm.groupCheckedKeys"
                        :check-strictly="!groupCheckStrictly"
                        empty-text="加载中，请稍候"
                        :props="{ label: 'groupName', children: 'children' }"
                    />
                </el-form-item>
                <el-form-item label="备注" prop="remark">
                    <el-input v-model="roleForm.remark" placeholder="请输入备注"/>
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="handleClose">取消</el-button>
                    <el-button type="primary" @click="handleSubmit">确定</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script>
import {getCurrentInstance , onMounted , reactive , ref , toRaw} from 'vue'
import utils from "../utils/utils";
export default {
    name:'role',
    setup(){
        // 获取Composition API 上下文对象
        const {ctx,proxy} = getCurrentInstance();
        //初始化角色表单对象
        const queryForm = reactive({});
        //初始化角色列表数据
        const roleList = ref([]);
        //初始化分页对象
        const pager = reactive({
            pageNum:1,
            pageSize:10
        });
        //选中角色列表的对象
        const checkedRoleIds = ref([]);
        //弹框显示对象
        const showModal = ref(false);
        //新增角色表单对象
        const roleForm = reactive({
            status:1
        });
        //菜单树
        const menuOptions = ref([]);
        //菜单选中结果
        const menuRef = ref(null);
        //菜单是否展开
        const menuExpand = ref(false);
        //菜单全选、全不选
        const menuNodeAll = ref(false);
        //菜单父子是否联动
        const menuCheckStrictly = ref(false);

        //组织树
        const groupOptions = ref([]);
        //组织选中结果
        const groupRef = ref(null);
        //组织是否展开
        const groupExpand = ref(false);
        //组织全选、全不选
        const groupNodeAll = ref(false);
        //组织父子是否联动
        const groupCheckStrictly = ref(false);
        //定义角色操作行为
        const action = ref('add');
        //定义表单校验规则
        const rules = reactive({
            rolename: [
                {
                required: true,
                message: "请输入角色名称",
                trigger: "blur",
                },
            ]
        });
        //定义动态表格格式
        const columns = reactive([
            {
                label: "角色名称",
                prop: "roleName",
                width: 150,
            },
            {
                label:'角色状态',
                prop:'status', 
                formatter(row,column,value){
                    return {
                        0:'停用',
                        1:'正常'
                    }[value]
                }
            },
            {
                label: "备注",
                prop: "remark",
            },
            {
                label: "创建时间",
                prop: "createTime",
                formatter(row, column, value) {
                    return utils.formateDate(new Date(value));
                },
            }
        ]);
        //初始化接口调用
        onMounted(()=>{
            getRoleList();
        })
        // 获取角色列表
        const getRoleList = async () => {
            let params = { ...queryForm, ...pager };
            try {
                const { list, total } = await proxy.$api.getRoleList(params);
                roleList.value = list;
                pager.totalCount = total;
            } catch (error) {
                console.log(proxy.$api);
            }
        };
        //查询事件，获取角色列表
        const handleQuery = () =>{
            getRoleList();
        }
        // 重置查询表单
        const handleReset = (form) => {
            proxy.$refs[form].resetFields();
            getRoleList();
        };
        // 分页事件处理
        const handleCurrentChange = (current) => {
            pager.pageNum = current;
            getRoleList();
        };
        //角色单个删除
        const handleDelete = async (row)=>{
            await proxy.$api.roleDelete({
                roleIds:[row.roleId]
            })
            proxy.$message.success('删除成功');
            getRoleList();
        }
        //批量删除
        const handlePatchDelete = async ()=>{
            if(checkedRoleIds.value.length == 0){
                proxy.$message.error('请选择要删除的角色');
                return;
            }
            const res = await proxy.$api.roleDelete({
                roleIds:checkedRoleIds.value
            })
            if(res.rows > 0){
                proxy.$message.success('删除成功');
                getRoleList();          
            }else{
                proxy.$message.error('删除失败');
            }
            
        }
        //表格多选
        const handleSelectionChange = (list)=>{
            let arr = [];
            list.map(item=>{
                arr.push(item.roleId);
            })
            checkedRoleIds.value = arr;
        }
        //角色新增
        const handleCreate = ()=>{
            getMenuTreeSelect();
            action.value = 'add';
            showModal.value = true;
        }
        // 角色弹窗关闭
        const handleClose = () => {
            showModal.value = false;
            menuExpand.value = false;
            menuNodeAll.value = false;
            menuCheckStrictly.value = false;
            groupExpand.value = false;
            groupNodeAll.value = false;
            groupCheckStrictly.value = false;
            handleReset("dialogForm");
        };
        // 角色提交
        const handleSubmit = () => {
            proxy.$refs.dialogForm.validate(async (valid) => {
                if (valid) {
                    let params = toRaw(roleForm);
                    params.action = action.value;
                    // 当前选中的菜单节点
                    let menuCheckedKeys = menuRef.value.getCheckedKeys();
                    // 当前选中的组织节点
                    let groupCheckedKeys = groupRef.value.getCheckedKeys();
                    // 当前半选中的菜单节点
                    let halfMenuCheckedKeys = menuRef.value.getHalfCheckedKeys();
                    // 当前半选中的组织节点
                    let halfGroupCheckedKeys = groupRef.value.getHalfCheckedKeys();
                    menuCheckedKeys.unshift.apply(menuCheckedKeys, halfMenuCheckedKeys);
                    groupCheckedKeys.unshift.apply(groupCheckedKeys, halfGroupCheckedKeys);
                    params.menuIds = menuCheckedKeys;
                    params.groupIds = groupCheckedKeys;
                    if(action.value == 'add'){
                        let res = await proxy.$api.roleSubmit(params);
                        proxy.$message.success("角色创建成功");
                    }else{
                        let res = await proxy.$api.roleUpdate(params);
                        proxy.$message.success("角色修改成功");
                        
                    }
                    showModal.value = false;
                    menuExpand.value = false;
                    menuNodeAll.value = false;
                    menuCheckStrictly.value = false;
                    groupExpand.value = false;
                    groupNodeAll.value = false;
                    groupCheckStrictly.value = false;
                    handleReset("dialogForm");
                    getRoleList();
                }
            });
        };
        // 角色编辑
        const handleEdit = (row) => {
            action.value = "edit";
            showModal.value = true;
            proxy.$nextTick(async () => {
                try {
                    const { role, menuList, menuCheckedKeys, groupList, groupCheckedKeys} = await proxy.$api.getRoleById({roleId:row.roleId});
                    Object.assign(roleForm, role);
                    menuOptions.value = menuList;
                    roleForm.menuCheckedKeys = menuCheckedKeys;
                    groupOptions.value = groupList;
                    roleForm.groupCheckedKeys = groupCheckedKeys;
                } catch (error) {
                    console.log(proxy.$api);
                }
            });
        };
        // 查询菜单树结构
        const getMenuTreeSelect = async () => {
            let list = await proxy.$api.getMenuList({});
            menuOptions.value = list;
        };
        // 菜单树（展开/折叠）
        const handleMenuCheckedTreeExpand = (value) => {
            let treeList = menuOptions.value;
            for (let i = 0; i < treeList.length; i++) {
            menuRef.value.store.nodesMap[treeList[i].menuId].expanded = value;
            }
        }
        // 菜单树（全选/全不选）
        const handleMenuCheckedTreeNodeAll = (value) => {
            menuRef.value.setCheckedNodes(value ? menuOptions.value : []);
        }
        // 菜单树（父子联动）
        const handleMenuCheckedTreeConnect = (value) => {
            menuCheckStrictly.value = value ? true : false;
        }
        // 组织树（展开/折叠）
        const handleGroupCheckedTreeExpand = (value) => {
            let treeList = groupOptions.value;
            for (let i = 0; i < treeList.length; i++) {
            groupRef.value.store.nodesMap[treeList[i].groupId].expanded = value;
            }
        }
        // 组织树（全选/全不选）
        const handleGroupCheckedTreeNodeAll = (value) => {
            groupRef.value.setCheckedNodes(value ? groupOptions.value : []);
        }
        // 组织树（父子联动）
        const handleGroupCheckedTreeConnect = (value) => {
            groupCheckStrictly.value = value ? true : false;
        }
        return {
            queryForm,
            roleList,
            columns,
            pager,
            checkedRoleIds,
            showModal,
            roleForm,
            menuOptions,
            menuRef,
            menuExpand,
            menuNodeAll,
            menuCheckStrictly,
            groupOptions,
            groupRef,
            groupExpand,
            groupNodeAll,
            groupCheckStrictly,
            action,
            rules,
            getRoleList,
            handleQuery,
            handleReset,
            handleCurrentChange,
            handleDelete,
            handlePatchDelete,
            handleSelectionChange,
            handleCreate,
            handleClose,
            handleSubmit,
            handleEdit,
            getMenuTreeSelect,
            handleMenuCheckedTreeExpand,
            handleMenuCheckedTreeNodeAll,
            handleMenuCheckedTreeConnect,
            handleGroupCheckedTreeExpand,
            handleGroupCheckedTreeNodeAll,
            handleGroupCheckedTreeConnect
        }
    }
}
</script>

<style lang="scss">

</style>